package game.Sprites;

import game.Vector3;
import javafx.scene.SnapshotParameters;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

import javafx.scene.paint.Color;

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

public class Spark extends Sprite {
    protected double speed;
    protected double size;
    protected float opacity;
    protected double lastDist;

    public Spark(Vector3 position, double rotation, Color color, double size, double speed) throws Exception {
        super(position, rotation, color);
        this.setZ(1.0);

        this.opacity = 1.f;
        this.size = size;
        this.speed = speed;
        this.lastDist = 0.2;
    }

    @Override
    public void draw(GraphicsContext g2D, Vector3 screenPos, double squareRes) {

        //Apply rotation
        ///ImageView iv = new ImageView(img);
        //iv.setRotate(Math.toDegrees(rotation));
        //SnapshotParameters params = new SnapshotParameters();
        // params.setFill(javafx.scene.paint.Color.TRANSPARENT);
        //Image rotatedImage = iv.snapshot(params, null);

        double rectWidth = lastDist * squareRes;

        // Draw rectangle
        double oldAlpha = g2D.getGlobalAlpha();
        //g2D.setGlobalAlpha(opacity);
        g2D.setStroke(color);
        double oldLineWidth = g2D.getLineWidth();
        g2D.setLineWidth(squareRes * size);

        Point2D center = new Point2D.Double(screenPos.x - squareRes * size / 2,
                screenPos.y - squareRes * size / 2);
        Point2D point0 = new Point2D.Double(center.getX() - Math.cos(rotation)*rectWidth/2,
                    center.getY() - Math.sin(rotation)*rectWidth/2);
        Point2D point2 = new Point2D.Double(center.getX() + Math.cos(rotation)*rectWidth/2,
                center.getY() + Math.sin(rotation)*rectWidth/2);


        g2D.strokeLine(point0.getX(),point0.getY(),point2.getX(),point2.getY());
        g2D.setLineWidth(oldLineWidth);
        //g2D.setGlobalAlpha(oldAlpha);
    }

    @Override
    public Rectangle2D.Double getBound() {
        return new Rectangle2D.Double(this.position.x - size/2, this.position.y - size/2, size, size);
    }

    @Override
    public void update(double deltaTime) {
        this.position = this.position.add(
                new Vector3(Math.cos(rotation), Math.sin(rotation), 0.0).multiply(speed).multiply(deltaTime)
        );

        this.opacity -= deltaTime * 2.0;
        if(this.opacity <= 0.0){
            this.destroy();
        }

        this.lastDist = speed*deltaTime;
        this.size = this.size * 0.7;
        this.speed = this.speed * 0.98;
    }
}
